// app/controller/procurement/supplier_evaluation_controller.js
'use strict';

const Controller = require('egg').Controller;

class SupplierEvaluationController extends Controller {
  // 获取评估列表
  async index() {
    const { ctx } = this;
    const { supplierId, status, page = 1, limit = 20 } = ctx.query;
    
    try {
      // 构建查询条件
      const whereClause = {};
      if (supplierId) {
        whereClause.supplierId = supplierId;
      }
      if (status) {
        whereClause.status = status;
      }
      
      // 查询数据
      const result = await ctx.model.SupplierEvaluationModel.findAndCountAll({
        where: whereClause,
        include: [{
          model: ctx.model.SupplierModel,
          as: 'supplier',
          attributes: ['id', 'name']
        }],
        order: [['createdAt', 'DESC']],
        limit: parseInt(limit),
        offset: (parseInt(page) - 1) * parseInt(limit)
      });
      
      // 转换数据格式
      const evaluations = result.rows.map(evaluation => ({
        id: evaluation.id,
        supplierId: evaluation.supplierId,
        evaluator: evaluation.evaluator,
        evaluationDate: evaluation.evaluationDate,
        qualityScore: evaluation.qualityScore,
        deliveryScore: evaluation.deliveryScore,
        serviceScore: evaluation.serviceScore,
        priceScore: evaluation.priceScore,
        overallScore: evaluation.overallScore,
        evaluationPeriod: evaluation.evaluationPeriod,
        status: evaluation.status,
        remark: evaluation.remark,
        createdAt: evaluation.createdAt,
        updatedAt: evaluation.updatedAt,
        supplier: evaluation.supplier ? {
          id: evaluation.supplier.id,
          name: evaluation.supplier.name
        } : null
      }));
      
      ctx.page(evaluations, result.count, parseInt(page), parseInt(limit));
    } catch (error) {
      ctx.logger.error('获取供应商评估列表失败:', error);
      ctx.error(`获取供应商评估列表失败: ${error.message}`);
    }
  }
  
  // 获取评估详情
  async show() {
    const { ctx } = this;
    const { id } = ctx.params;
    
    try {
      const evaluation = await ctx.model.SupplierEvaluationModel.findByPk(id, {
        include: [{
          model: ctx.model.SupplierModel,
          as: 'supplier',
          attributes: ['id', 'name']
        }]
      });
      
      if (!evaluation) {
        ctx.error('评估记录不存在', 404);
        return;
      }
      
      ctx.success({
        id: evaluation.id,
        supplierId: evaluation.supplierId,
        evaluator: evaluation.evaluator,
        evaluationDate: evaluation.evaluationDate,
        qualityScore: evaluation.qualityScore,
        deliveryScore: evaluation.deliveryScore,
        serviceScore: evaluation.serviceScore,
        priceScore: evaluation.priceScore,
        overallScore: evaluation.overallScore,
        evaluationPeriod: evaluation.evaluationPeriod,
        status: evaluation.status,
        remark: evaluation.remark,
        createdAt: evaluation.createdAt,
        updatedAt: evaluation.updatedAt,
        supplier: evaluation.supplier ? {
          id: evaluation.supplier.id,
          name: evaluation.supplier.name
        } : null
      });
    } catch (error) {
      ctx.logger.error('获取供应商评估详情失败:', error);
      ctx.error(`获取供应商评估详情失败: ${error.message}`);
    }
  }
  
  // 创建评估
  async create() {
    const { ctx } = this;
    const evaluationData = ctx.request.body;
    
    try {
      // 使用Joi验证服务进行参数验证
      const validation = ctx.service.validationService.validateCreateSupplierEvaluation(evaluationData);
      if (validation.error) {
        ctx.error(`参数验证失败: ${validation.error.message}`);
        return;
      }
      
      const { supplierId, evaluator, qualityScore, deliveryScore, serviceScore, priceScore, evaluationPeriod, status, remark } = evaluationData;
      
      // 计算综合评分
      const overallScore = ((parseFloat(qualityScore) + parseFloat(deliveryScore) + parseFloat(serviceScore) + parseFloat(priceScore)) / 4).toFixed(2);
      
      // 创建评估
      const evaluation = await ctx.model.SupplierEvaluationModel.create({
        supplierId,
        evaluator,
        qualityScore,
        deliveryScore,
        serviceScore,
        priceScore,
        overallScore,
        evaluationPeriod,
        status: status || 'draft',
        remark
      });
      
      ctx.success({
        id: evaluation.id
      }, '评估创建成功');
    } catch (error) {
      ctx.logger.error('创建供应商评估失败:', error);
      ctx.error(`创建供应商评估失败: ${error.message}`);
    }
  }
  
  // 更新评估
  async update() {
    const { ctx } = this;
    const { id } = ctx.params;
    const evaluationData = ctx.request.body;
    
    try {
      // 使用Joi验证服务进行参数验证
      // 首先验证ID
      const idValidation = ctx.service.validationService.validateId(parseInt(id));
      if (idValidation.error) {
        ctx.error(`参数验证失败: ${idValidation.error.message}`);
        return;
      }
      
      // 验证评估数据
      const validation = ctx.service.validationService.validateUpdateSupplierEvaluation(evaluationData);
      if (validation.error) {
        ctx.error(`参数验证失败: ${validation.error.message}`);
        return;
      }
      
      const { supplierId, evaluator, qualityScore, deliveryScore, serviceScore, priceScore, evaluationPeriod, status, remark } = evaluationData;
      
      const evaluation = await ctx.model.SupplierEvaluationModel.findByPk(id);
      if (!evaluation) {
        ctx.error('评估记录不存在', 404);
        return;
      }
      
      // 计算综合评分
      let overallScore = evaluation.overallScore;
      if (qualityScore || deliveryScore || serviceScore || priceScore) {
        const qScore = qualityScore !== undefined ? parseFloat(qualityScore) : parseFloat(evaluation.qualityScore);
        const dScore = deliveryScore !== undefined ? parseFloat(deliveryScore) : parseFloat(evaluation.deliveryScore);
        const sScore = serviceScore !== undefined ? parseFloat(serviceScore) : parseFloat(evaluation.serviceScore);
        const pScore = priceScore !== undefined ? parseFloat(priceScore) : parseFloat(evaluation.priceScore);
        overallScore = ((qScore + dScore + sScore + pScore) / 4).toFixed(2);
      }
      
      // 更新评估
      await evaluation.update({
        supplierId,
        evaluator,
        qualityScore,
        deliveryScore,
        serviceScore,
        priceScore,
        overallScore,
        evaluationPeriod,
        status,
        remark
      });
      
      ctx.success(null, '评估更新成功');
    } catch (error) {
      ctx.logger.error('更新供应商评估失败:', error);
      ctx.error(`更新供应商评估失败: ${error.message}`);
    }
  }
  
  // 删除评估
  async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;
    
    try {
      const evaluation = await ctx.model.SupplierEvaluationModel.findByPk(id);
      if (!evaluation) {
        ctx.error('评估记录不存在', 404);
        return;
      }
      
      // 删除评估
      await evaluation.destroy();
      
      ctx.success(null, '评估删除成功');
    } catch (error) {
      ctx.logger.error('删除供应商评估失败:', error);
      ctx.error(`删除供应商评估失败: ${error.message}`);
    }
  }
  
  // 获取供应商的评估统计
  async getSupplierStats() {
    const { ctx } = this;
    const { supplierId } = ctx.query;
    
    try {
      if (!supplierId) {
        ctx.error('供应商ID不能为空', 400);
        return;
      }
      
      // 查询该供应商的所有评估记录
      const evaluations = await ctx.model.SupplierEvaluationModel.findAll({
        where: { supplierId },
        order: [['createdAt', 'DESC']]
      });
      
      if (evaluations.length === 0) {
        ctx.success({
          count: 0,
          averageScore: 0,
          latestEvaluation: null
        });
        return;
      }
      
      // 计算平均分
      const totalScore = evaluations.reduce((sum, evaluation) => sum + parseFloat(evaluation.overallScore), 0);
      const averageScore = (totalScore / evaluations.length).toFixed(2);
      
      // 最新评估
      const latestEvaluation = evaluations[0];
      
      ctx.success({
        count: evaluations.length,
        averageScore: parseFloat(averageScore),
        latestEvaluation: {
          id: latestEvaluation.id,
          evaluationDate: latestEvaluation.evaluationDate,
          overallScore: parseFloat(latestEvaluation.overallScore),
          status: latestEvaluation.status
        }
      });
    } catch (error) {
      ctx.logger.error('获取供应商评估统计失败:', error);
      ctx.error(`获取供应商评估统计失败: ${error.message}`);
    }
  }
}

module.exports = SupplierEvaluationController;